﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Home.Framework.Infrastructure
{
    public static partial class EnumUtils
    {
        /// <summary>
        /// 获取枚举类型的int数组
        /// </summary>
        /// <typeparam name="TEnum">The type of the t enum.</typeparam>
        /// <returns>System.Int32[][].</returns>
        public static int[] GetIntValues<TEnum>()
        {
            int index = 0;
            Array enums = Enum.GetValues(typeof(TEnum));
            int[] values = new int[enums.Length];
            foreach (var value in enums)
            {
                values[index++] = (int)value;
            }
            return values;
        }

        /// <summary>
        /// 检查指定枚举名在枚举类中是否存在
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="name">枚举名称</param>
        /// <returns><c>true</c> if the specified name contains name; otherwise, <c>false</c>.</returns>
        public static bool ContainsName<TEnum>(string name)
        {
            return Enum.GetNames(typeof(TEnum)).Contains(name);
        }

        /// <summary>
        /// 判断枚举类型是否包含指定的枚举值
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="value">枚举值</param>
        /// <returns><c>true</c> if the specified value contains value; otherwise, <c>false</c>.</returns>
        public static bool ContainsValue<TEnum>(int value)
        {
            return Enum.IsDefined(typeof(TEnum),value);
        }

        /// <summary>
        /// 获取枚举对象的名称，若该对象为NULL返回空字符串
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="target">枚举值</param>
        /// <returns>枚举值名称</returns>
        public static string GetName<TEnum>(TEnum target)
        {
            if (target != null)
            {
                return Enum.GetName(target.GetType(), target);
            }
            return string.Empty;
        }

        /// <summary>
        /// 根据枚举值获取int值的泛型方法
        /// 在实际类型中可通过(int)target来强制转换
        /// </summary>
        /// <typeparam name="TEnum">The type of the t enum.</typeparam>
        /// <param name="target">The target.</param>
        /// <returns>System.Int32.</returns>
        public static int GetValue<TEnum>(TEnum target)
        {
            if (target != null)
            {
                return (int)Enum.Parse(typeof(TEnum), target.ToString());
            }
            return int.MinValue;
        }
    }
}
